import mysql.connector
import os,sys
from datetime import datetime
from qcloud_cos import CosConfig, CosS3Client

# 配置 COS SDK
secret_id = "AKIDYy95mGWXIo69wTs3yd5KK4auzoOjpfGc"
secret_key = "81f4FBtMbbLq7AELNDznU0LSL1SecNs9"
region = "ap-hongkong"
bucket = "hcecpod-1343049753"

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)

def get_all_filepath(folder_path):
    paths = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            return_path=os.path.join(root, file).replace('\\','/')
            paths.append(return_path)
    return paths

def upload_file(local_path,cos_path):
    if os.path.isfile(local_path):
        try:
            client.upload_file(Bucket=bucket, LocalFilePath=local_path, Key=cos_path)
            return True
        except:
            return False
        
def upload_hidden_model(category):
    # 数据库连接信息（请修改为你的数据库信息）
    db_config = {
        "host": "43.161.240.94",
        "user": "hcecpod_com",
        "password": "Xcd9sMZ9DMBBkbMf",
        "database": "hcecpod_com",
    }

    dir='D:/Desk/系统图库/model/'+category
    paths=get_all_filepath(dir)
    print(category+'底板文件集中有：',len(paths))
    # 连接数据库
    conn = mysql.connector.connect(**db_config)
    mycursor = conn.cursor()
    mycursor.execute("select id,path from data_model where category='"+category+"' and belong='小成'")
    myresult = mycursor.fetchall()
    hidden_ids=[]
    for x in myresult:
        if x[1] not in paths:
            hidden_ids.append(x[0])
        else:
            paths.remove(x[1])
    print(category+'不在底板文件集中有：',len(paths))
    now = datetime.now()
    formatted_date = now.strftime("%Y-%m-%d")
    sql = f"update data_model set hidden='{formatted_date+'hidden'}' where id in ({', '.join(map(str, hidden_ids))})"
    mycursor.execute(sql)
    conn.commit()
    print(mycursor.rowcount,"个数据被隐藏")
    # return
    for path in paths:
        file_name=os.path.basename(path)
        mycursor.execute("select max(id) from data_model") 
        myresult = mycursor.fetchone()
        begin_id=myresult[0]+1
        dict=[]
        name='DB' +str(begin_id + 1000)
        pic=name+os.path.splitext(file_name)[1]
        dict.append(name)
        dict.append(pic)
        dict.append(path)
        dict.append(path.split('/')[4])
        if category=='全球女装':
            topic=path.split('/')[5].split('#')[0]
            dict.append(topic)      
            dict.append(path.split('/')[6])        
            dict.append(formatted_date)        
            dict.append("镜像添加")
            style_name=path.split('/')[5].split('#')[1]+'#'+path.split('/')[6]
            dict.append(style_name)
        if path.split('/')[4]=='全球男装':
            topic=path.split('/')[5].split('#')[0]
            style_name=path.split('/')[5].split('#')[1]+'#'+path.split('/')[6]
            dict.append(topic.split('-')[1])      
            dict.append(path.split('/')[6])        
            dict.append(formatted_date)        
            dict.append("镜像添加")
            dict.append(style_name)
        if path.split('/')[4]=='全球童装':
            topic=path.split('/')[5].split('#')[0]
            dict.append(topic)      
            dict.append(path.split('/')[6])        
            dict.append(formatted_date)        
            dict.append("镜像添加")
            style_name=path.split('/')[5].split('#')[1]+'#'+path.split('/')[6]
            dict.append(style_name)
        if path.split('/')[4]=='亚洲女装':
            dict.append('默认')
            dict.append(path.split('/')[6])        
            dict.append(formatted_date)        
            dict.append("镜像添加")
            a=path.split('/')[5]
            style_name=a.split('-')[1]+'#'+path.split('/')[6]
            dict.append(style_name)
        dict=tuple(dict)
        if(upload_file(path,'model/'+pic)):
            try:
                sql = "insert into data_model (name,pic,path,category,topic,color,date,add_sort,style_name) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)" 
                mycursor.execute(sql,dict) 
                conn.commit()
                print('success:',path)
            except:                
                print('error:',path)
                continue
            
categorys=['全球男装','全球童装','亚洲女装','全球女装']
for category in categorys:
    upload_hidden_model(category)